<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 社区查询 -->
      <el-form-item label="社区" prop="communityId">
        <el-select
            v-model="queryParams.communityId"
            placeholder="请选择社区"
            clearable
            @change="handleQueryCommunityChange"
            style="width: 120px"
        >
          <el-option
              v-for="c in queryCommunityList"
              :key="c.communityId"
              :label="c.name"
              :value="c.communityId"
          />
        </el-select>
      </el-form-item>

      <!-- 楼宇查询 -->
      <el-form-item label="楼宇" prop="buildingId">
        <el-select
            v-model="queryParams.buildingId"
            placeholder="请选择楼宇"
            clearable
            @change="handleQueryBuildingChange"
            style="width: 120px"
        >
          <el-option
              v-for="b in queryBuildingList"
              :key="b.buildingId"
              :label="b.name"
              :value="b.buildingId"
          />
        </el-select>
      </el-form-item>

      <!-- 房间号查询 -->
      <el-form-item label="房间号" prop="roomId">
        <el-select
            v-model="queryParams.roomId"
            placeholder="请先选择楼宇"
            clearable
            filterable
            :disabled="!queryParams.buildingId"
            style="width: 120px"
        >
          <el-option
              v-for="h in queryHouseList"
              :key="h.houseId"
              :label="h.roomNo"
              :value="h.houseId"
          />
        </el-select>
      </el-form-item>

      <!--支付状态查询-->
      <el-form-item label="支付状态" prop="paymentStatus">
        <el-select
            v-model="queryParams.paymentStatus"
            placeholder="支付状态"
            clearable
            style="width: 120px"
        >
          <el-option label="已支付" :value="0" />
          <el-option label="未支付" :value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="费用" prop="amount">
        <el-input
            v-model="queryParams.amount"
            placeholder="请输入费用"
            clearable
            @keyup.enter="handleQuery"
            style="width: 120px"
        />
      </el-form-item>

      <el-form-item label="抄表时间" prop="readingTime">
        <el-date-picker
            clearable
            v-model="queryParams.readingTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择抄表时间"
            style="width: 140px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['charge:records:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['charge:records:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['charge:records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['charge:records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="社区" align="center" prop="communityName" />
      <el-table-column label="楼宇" align="center" prop="buildingName" />
      <el-table-column label="房间" align="center" prop="roomNo" />
      <el-table-column label="收费项目" align="center" prop="chargeItemName" />
      <el-table-column label="缴费周期" align="center" prop="paymentCycle" />
      <el-table-column label="费用" align="center" prop="amount" />

      <el-table-column label="支付状态" align="center" prop="paymentStatus">
        <template #default="scope">
          <el-tag :type="scope.row.paymentStatus === 0 ? 'success' : 'warning'">
            {{ scope.row.paymentStatus === 0 ? '已支付' : '未支付' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="抄表时间" align="center" prop="readingTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.readingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['charge:records:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['charge:records:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改抄表账单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="社区" prop="communityId">
          <el-select
              v-model="form.communityId"
              placeholder="请选择社区"
              clearable
              @change="handleCommunityChange"
              style="width: 100%"
          >
            <el-option
                v-for="c in community"
                :key="c.communityId"
                :label="c.name"
                :value="c.communityId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="楼宇" prop="buildingId">
          <el-select
              v-model="form.buildingId"
              placeholder="请选择楼宇"
              clearable
              @change="handleBuildingChange"
              style="width: 100%"
          >
            <el-option
                v-for="b in building"
                :key="b.buildingId"
                :label="b.name"
                :value="b.buildingId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="房间号" prop="roomId">
          <el-select
              v-model="form.roomId"
              placeholder="请选择房间号"
              clearable
              style="width: 100%"
              :key="houseSelectKey"
          >
            <el-option
                v-for="h in house"
                :key="h.houseId"
                :label="h.roomNo || `房间${h.houseId}`"
                :value="h.houseId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="收费项目" prop="chargeItemId">
          <el-select
              v-model="form.chargeItemId"
              placeholder="请选择收费项目"
              clearable
              @change="handleChargeItemChange"
              style="width: 100%"
          >
            <el-option
                v-for="i in chargeItem"
                :key="i.chargeItemId"
                :label="i.name"
                :value="i.chargeItemId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上期表底" prop="lastReading">
          <el-input v-model="form.lastReading" placeholder="请输入上期表底" />
        </el-form-item>

        <el-form-item label="本期表底" prop="currentReading">
          <el-input v-model="form.currentReading" placeholder="请输入本期表底" />
        </el-form-item>

        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请选择收费项目后自动填写" readonly />
        </el-form-item>

        <el-form-item label="抄表时间" prop="readingTime">
          <el-date-picker
              clearable
              v-model="form.readingTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择抄表时间"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="缴费周期" prop="paymentCycle">
          <el-date-picker
              v-model="form.paymentCycle"
              type="month"
              value-format="YYYY-MM"
              placeholder="请选择缴费周期"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listRecords, getRecords, delRecords, addRecords, updateRecords } from "@/api/charge/records"
import request from '@/utils/request'

const { proxy } = getCurrentInstance()

// 响应式数据
const recordsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const houseSelectKey = ref(0)

// 查询用的下拉框数据
const queryCommunityList = ref([])
const queryBuildingList = ref([])
const queryHouseList = ref([])
const allBuildings = ref([])

// 表单用的下拉框数据
const community = ref([])
const building = ref([])
const house = ref([])
const chargeItem = ref([])

// 表单数据
const form = ref({
  communityId: null,
  buildingId: null,
  roomId: null,
  chargeItemId: null,
  id: null,
  paymentCycle: null,
  lastReading: null,
  currentReading: null,
  unitPrice: null,
  readingTime: null,
  remark: null,
  paymentStatus: 1,
})

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  amount: null,
  readingTime: null,
  communityId: null,
  buildingId: null,
  roomId: null,
  chargeItemId: null,
  paymentCycle: null,
  paymentStatus: null,
})

const rules = {
  communityId: [
    { required: true, message: "请选择社区", trigger: "change" }
  ],
  buildingId: [
    { required: true, message: "请选择楼宇", trigger: "change" }
  ],
  roomId: [
    { required: true, message: "请选择房间号", trigger: "change" }
  ],
  chargeItemId: [
    { required: true, message: "请选择收费项目", trigger: "change" }
  ],
  paymentCycle: [
    { required: true, message: "请选择缴费周期", trigger: "change" }
  ],
  lastReading: [
    { required: true, message: "上期表底不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的数字格式", trigger: "blur" }
  ],
  currentReading: [
    { required: true, message: "本期表底不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的数字格式", trigger: "blur" }
  ],
  unitPrice: [
    { required: true, message: "单价不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的数字格式", trigger: "blur" }
  ],
  readingTime: [
    { required: true, message: "请选择抄表时间", trigger: "change" }
  ]
}

/** 查询抄表账单列表 */
function getList() {
  loading.value = true
  listRecords(queryParams.value).then(response => {
    recordsList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(error => {
    console.error('查询失败:', error)
    loading.value = false
    proxy.$modal.msgError("查询失败")
  })
}

/** 初始化查询用的社区列表 */
const initQueryCommunity = () => {
  return request({
    url: `/communityVo/getCommunityVoNameById`,
    method: 'get'
  }).then((response) => {
    queryCommunityList.value = response.data || []
  }).catch(error => {
    console.error('加载查询社区失败:', error)
    queryCommunityList.value = []
  })
}

/** 加载所有楼宇 */
const loadAllBuildings = () => {
  return request({
    url: `/building/getBuildingVoIdAndName`,
    method: 'get'
  }).then((response) => {
    allBuildings.value = response.data || []
    queryBuildingList.value = [...allBuildings.value]
  }).catch(error => {
    console.error('加载楼宇列表失败:', error)
    queryBuildingList.value = []
  })
}

/** 查询社区改变时加载楼宇 */
const handleQueryCommunityChange = (communityId) => {
  queryParams.value.buildingId = null
  queryParams.value.roomId = null
  queryBuildingList.value = []
  queryHouseList.value = []

  if (communityId) {
    request({
      url: `/building/getBuildingVoNameAndId/${communityId}`,
      method: 'get'
    }).then((response) => {
      queryBuildingList.value = response.data || []
    }).catch(error => {
      console.error('根据社区加载楼宇失败:', error)
      queryBuildingList.value = []
    })
  } else {
    loadAllBuildings()
  }
}

/** 查询楼宇改变时加载房屋 */
const handleQueryBuildingChange = (buildingId) => {
  queryParams.value.roomId = null
  queryHouseList.value = []

  if (buildingId) {
    request({
      url: `/houseVo/getHouseVoNameAndId/${buildingId}`,
      method: 'get'
    }).then((response) => {
      queryHouseList.value = (response.data || []).map(item => ({
        ...item,
        houseId: Number(item.houseId)
      }))
    }).catch(error => {
      console.error('根据楼宇加载房屋失败:', error)
      queryHouseList.value = []
    })
  }
}

/** 初始化表单用的社区列表 */
const initCommunity = () => {
  return request({
    url: `/communityVo/getCommunityVoNameById`,
    method: 'get'
  }).then((response) => {
    community.value = response.data || []
  }).catch(error => {
    console.error('加载社区失败:', error)
    community.value = []
  })
}

/** 表单社区联动楼宇 */
const handleCommunityChange = async (communityId) => {
  form.value.buildingId = null
  form.value.roomId = null
  building.value = []
  house.value = []

  if (communityId) {
    try {
      const response = await request({
        url: `/building/getBuildingVoNameAndId/${communityId}`,
        method: 'get'
      })
      building.value = response.data || []
    } catch (error) {
      console.error('加载楼宇失败:', error)
      building.value = []
    }
  }
}

/** 表单楼宇联动房屋 */
const handleBuildingChange = async (buildingId) => {
  form.value.roomId = null
  house.value = []

  if (buildingId) {
    try {
      const response = await request({
        url: `/houseVo/getHouseVoNameAndId/${buildingId}`,
        method: 'get'
      })

      // 修复：确保数据类型一致并包含 roomNo
      house.value = (response.data || []).map(item => ({
        ...item,
        houseId: Number(item.houseId),
        roomNo: item.roomNo || `房间${item.houseId}`
      }))

      houseSelectKey.value += 1
    } catch (error) {
      console.error('加载房屋失败:', error)
      house.value = []
    }
  }
}

/** 表单收费项目下拉框 */
const initChargeItem = () => {
  return request({
    url: `/charge/itema/getChargeItem`,
    method: 'get'
  }).then((response) => {
    chargeItem.value = response.data || []
  }).catch(error => {
    console.error('加载收费项目失败:', error)
    chargeItem.value = []
  })
}

/** 收费项目改变时自动获取单价 */
const handleChargeItemChange = (chargeItemId) => {
  if (chargeItemId) {
    const selectedItem = chargeItem.value.find(item => item.chargeItemId == chargeItemId)
    if (selectedItem && selectedItem.price !== undefined && selectedItem.price !== null) {
      form.value.unitPrice = selectedItem.price
    } else {
      form.value.unitPrice = null
    }
  } else {
    form.value.unitPrice = null
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加抄表账单"

  // 确保数据已加载
  Promise.all([
    initCommunity(),
    initChargeItem()
  ])
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value[0]

  try {
    // 确保基础数据已加载
    await Promise.all([
      initCommunity(),
      initChargeItem()
    ])

    const response = await getRecords(_id)
    const recordData = response.data

    // 设置基础字段
    Object.assign(form.value, {
      id: recordData.id,
      chargeItemId: recordData.chargeItemId,
      paymentCycle: recordData.paymentCycle,
      lastReading: recordData.lastReading,
      currentReading: recordData.currentReading,
      unitPrice: recordData.unitPrice,
      readingTime: recordData.readingTime,
      remark: recordData.remark,
      paymentStatus: recordData.paymentStatus || 1
    })

    // 处理联动字段
    if (recordData.communityId) {
      form.value.communityId = recordData.communityId

      // 等待楼宇数据加载
      await handleCommunityChange(recordData.communityId)
      await new Promise(resolve => setTimeout(resolve, 200))

      if (recordData.buildingId) {
        form.value.buildingId = recordData.buildingId

        // 等待房屋数据加载
        await handleBuildingChange(recordData.buildingId)
        await new Promise(resolve => setTimeout(resolve, 200))

        // 关键修复：设置房间号
        if (recordData.roomId) {
          const roomId = Number(recordData.roomId)
          form.value.roomId = roomId
        }
      }
    }

    // 设置收费项目单价
    if (recordData.chargeItemId) {
      handleChargeItemChange(recordData.chargeItemId)
    }

    open.value = true
    title.value = "修改抄表账单"

    // 等待对话框渲染完成
    await proxy.$nextTick()
    await new Promise(resolve => setTimeout(resolve, 300))

    // 再次强制重新渲染房屋下拉框
    houseSelectKey.value += 1

  } catch (error) {
    console.error('获取数据失败:', error)
    proxy.$modal.msgError("获取数据失败")
  }
}

// 表单重置
function reset() {
  form.value = {
    communityId: null,
    buildingId: null,
    roomId: null,
    chargeItemId: null,
    id: null,
    paymentCycle: null,
    lastReading: null,
    currentReading: null,
    unitPrice: null,
    readingTime: null,
    remark: null,
    paymentStatus: 1,
  }
  building.value = []
  house.value = []
  houseSelectKey.value += 1
  if (proxy.$refs.recordsRef) {
    proxy.$refs.recordsRef.resetFields()
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.recordsRef.validate(valid => {
    if (valid) {
      const submitData = { ...form.value }

      if (form.value.id != null) {
        updateRecords(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(error => {
          console.error('修改失败:', error)
          proxy.$modal.msgError("修改失败")
        })
      } else {
        addRecords(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(error => {
          console.error('新增失败:', error)
          proxy.$modal.msgError("新增失败")
        })
      }
    }
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  if (proxy.$refs.queryRef) {
    proxy.$refs.queryRef.resetFields()
  }
  queryParams.value.communityId = null
  queryParams.value.buildingId = null
  queryParams.value.roomId = null
  queryBuildingList.value = []
  queryHouseList.value = []
  loadAllBuildings()
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除抄表账单编号为"' + _ids + '"的数据项？').then(function() {
    return delRecords(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('charge/records/export', {
    ...queryParams.value
  }, `records_${new Date().getTime()}.xlsx`)
}

// 时间格式化函数
const parseTime = (time, format) => {
  if (!time) return ''
  try {
    const date = new Date(time)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    if (format === '{y}-{m}-{d}') {
      return `${year}-${month}-${day}`
    }
    return time
  } catch (error) {
    return time
  }
}

// 初始化
onMounted(() => {
  getList()
  initQueryCommunity()
  loadAllBuildings()
  initCommunity()
  initChargeItem()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>